from datetime import datetime
from typing import List

from connector.scenarioConnector import scenarioConnector
from connector.stockConnector import stockConnector



class AnalyzerService:
    def __init__(self) -> None:
        return 
    
    def analyzerStock(self,analyzer_form)->dict:
        scenario_id = analyzer_form['scenario_id']
        scenario = scenarioConnector.getScenarioById(scenario_id)
        stock_code = stockConnector.getStockCodeById(analyzer_form['stock_id'])
        analyzer_item_list = []
        for i in scenario.item_list:
            analyzer_item_list.append({
                'date':datetime.fromtimestamp(i['end_date'])
            })
        for i in analyzer_form['item_attribute_list']:
            analyzer_form[i['label']] = i['value']
        for i in analyzer_item_list:
            i['open'] = stockConnector.getAttributeOfStockOnDate(stock_code,i['date'],'open')
            i['close'] = stockConnector.getAttributeOfStockOnDate(stock_code,i['date'],'open')
            i['high'] = stockConnector.getAttributeOfStockOnDate(stock_code,i['date'],'open')
            i['low'] = stockConnector.getAttributeOfStockOnDate(stock_code,i['date'],'open')
            for j in analyzer_form['item_attribute_list']:
                i[j['label']] = scenarioConnector.getAttributeDataOnDate(scenario_id,j['label'],i['date'])
        

                
        for i in analyzer_item_list:
            temp_sum = 0
            for key in i:
                if key != 'date':
                    temp_sum += (analyzer_form[key] - i[key])**2
            i['variance'] =  temp_sum**(1/2)
        
        
        inverse_variances = [1 / item['variance'] for item in analyzer_item_list if item['variance'] > 0]

        # 计算倒数的总和
        sum_inverse_variances = sum(inverse_variances)

        # 分配权重
        for item in analyzer_item_list:
            if item['variance'] > 0:
                item['weight'] = (1 / item['variance']) / sum_inverse_variances
            else:
                item['weight'] = 0

        for i in analyzer_item_list:
            i['predict_open'] = stockConnector.getAttributeOfStockOnDate(stock_code,i['date'],'open',3)
            i['predict_close'] = stockConnector.getAttributeOfStockOnDate(stock_code,i['date'],'close',3)
            i['predict_high'] = stockConnector.getAttributeOfStockOnDate(stock_code,i['date'],'high',3)
            i['predict_low'] = stockConnector.getAttributeOfStockOnDate(stock_code,i['date'],'low',3)
            i['bound_close'] = stockConnector.getAttributeOfStockOnDate(stock_code,i['date'],'close',15)
        return analyzer_item_list




